import json
from socket import *

ADDR = ('127.0.0.1', 8000)
# 所有函数都用s
s = socket()
s.connect(ADDR)


def do_hist(name):
    msg = 'H %s' % name
    s.send(msg.encode())
    history_words = s.recv(1024).decode()
    if history_words:
        history_word_list = json.loads(history_words)
        for name, word, times in history_word_list:
            print('%s:%s' % (word, times))
    else:
        print('没有找到历史记录')


def do_query(name):
    """
        查询单词
    :param name: 用户名
    :return: void
    """
    while True:
        word = input('请输入单词:')
        if word == '###':
            break
        s.send(('Q %s %s' % (word, name)).encode())
        means = s.recv(1024).decode()
        print(means)


def login(name):
    """
        登录成功
    :param name: 用户名
    :return: void
    """
    while True:
        print("""
        =====================Query===============
            1.查单词      2.历史记录       3.注销
        =========================================
        """)
        cmd = input('输入选项:')
        if cmd == '1':
            do_query(name)
        elif cmd == '2':
            do_hist(name)
        elif cmd == '3':
            return
        else:
            print('请输入正确命令')


def do_register():
    while True:
        name = input('User:')
        passwd = input('password:')
        passwd1 = input('again password:')
        # passwd = getpass('password')
        # passwd1 = getpass('Again:')
        if (' ' in name) or (' ' in passwd):
            print('用户名或密码不能有空格')
            continue
        if passwd != passwd1:
            print('两次密码不一致')
            continue
        # 注册R开头报文格式
        msg = 'R %s %s' % (name, passwd)
        # 发送请求
        s.send(msg.encode())
        # 接收反馈
        data = s.recv(128).decode()

        if data == 'OK':
            print('注册成功')
            login(name)
            return
        else:
            print("注册失败")
            return


def do_login():
    name = input('请输入用户名:')
    passwd = input('请输入密码:')
    msg = "L %s %s" % (name, passwd)
    s.send(msg.encode())
    data = s.recv(128).decode()
    if data == 'OK':
        print('登录成功')
        login(name)
    else:
        return


def main():
    while True:
        print("""
        ==================Welcome=========================
            1.注册        2.登录        3.退出
        ==================================================
        """)
        cmd = input("请输入选项")
        if cmd == '1':
            do_register()
        elif cmd == '2':
            do_login()
        elif cmd == '3':
            s.send(b'E')
            print('感谢使用')
            return
        else:
            print('请输入正确命令!')


if __name__ == "__main__":
    main()
